/**
 * 
 */
package homework5;

import java.util.LinkedList;

/**
 * @author Nican
 * 
 */
public abstract class NetworkFinderAbstract<E> {

	final Graph graph;
	LinkedList<Node> usedNodes;

	public NetworkFinderAbstract(Graph graph) {
		this.graph = graph;
	}
	
	/**
	 * Analyzes a node, and checks if it not already used, and find all neibhors towns
	 * @param node
	 * @param subGraphs
	 */
	public void analyzideNode(Node node, LinkedList<LinkedList<E>> subGraphs) {
		
		//Checks if the city was not already used it
		if (usedNodes.contains(node))
			return;

		LinkedList<E> subGraph = new LinkedList<E>();
		
		//Find all nodes that are connected to this node
		getAllNeighbors(node, subGraph);

		subGraphs.add(subGraph);

	}
	
	/**
	 * Get all the neighbors in a node, and add them all to the list
	 * @param node
	 * @param list
	 */
	private void getAllNeighbors(Node node, LinkedList<E> list) {
		
		//Node already used before
		if (usedNodes.contains(node))
			return;
		
		usedNodes.add(node);
		
		//Add the node value to the final list
		list.add(getNodeValue(node));
		
		//Look at all the nodes around it, and add to the current subgraph
		for (Node neighbor : node.neighbors) {
			getAllNeighbors(neighbor, list);
		}

	}

	protected abstract E getNodeValue(Node e);

	public LinkedList<LinkedList<E>> finalSubGraphs() {
		LinkedList<LinkedList<E>> subGraphs = new LinkedList<LinkedList<E>>();
		usedNodes = new LinkedList<Node>();

		for (Node node : graph.nodes) {
			analyzideNode(node, subGraphs);
		}

		return subGraphs;
	}

}
